package com.yunfeng.supercall.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.http.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;

import com.ly.quickdev.library.adapter.ListBaseAdapter.ViewHolder;
import com.ly.quickdev.library.utils.JsonUtils;
import com.t9search.util.PinyinUtil;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.activity.AddSuperFriendsActivity;
import com.yunfeng.supercall.activity.BaseActivity;
import com.yunfeng.supercall.activity.ChatActivity;
import com.yunfeng.supercall.activity.FriendsDetailActivity;
import com.yunfeng.supercall.activity.MainActivity.DialPadSwitch;
import com.yunfeng.supercall.activity.NotAFriendsActivity;
import com.yunfeng.supercall.activity.OutCallActivity;
import com.yunfeng.supercall.activity.SearchUserActivity;
import com.yunfeng.supercall.adapter.ContactsDialPadAdapter;
import com.yunfeng.supercall.bean.PhoneContactsBean;
import com.yunfeng.supercall.bean.RecentCallsBean;
import com.yunfeng.supercall.bean.SuperFriendsBean;
import com.yunfeng.supercall.contactsutils.ContactsHelper;
import com.yunfeng.supercall.httputils.MyAjaxCallBack;
import com.yunfeng.supercall.manager.ManagerFactory;
import com.yunfeng.supercall.manager.SuperFriendsManager;
import com.yunfeng.supercall.service.CallConnectionService;
import com.yzx.api.UCSService;

/**
 * 拨号页面
 * 
 * @author 洋
 * 
 */
public class DialPadFragment extends BaseFragment implements DialPadSwitch {

	public static final Map<String, Boolean> IS_SUPER = new HashMap<String, Boolean>();

	/**
	 * 拨号键盘
	 * 
	 * @author 洋
	 * 
	 */
	class GridAdapter extends BaseAdapter {
		private int mHeight;

		public GridAdapter() {
		}

		@Override
		public int getCount() {
			return 12;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = mContext.getLayoutInflater().inflate(
						R.layout.grid_item_dial_pad, null);

			}

			int one = getResources()
					.getDimensionPixelOffset(R.dimen.grid_space);
			mHeight = (mGridView.getHeight() - ((getCount() / 3) - 1) * one)
					/ (getCount() / 3);
			LayoutParams layoutParams = new LayoutParams(
					LayoutParams.FILL_PARENT, mHeight);

			convertView.setLayoutParams(layoutParams);
			TextView tv = ViewHolder.get(convertView, R.id.nums);
			TextView chars = ViewHolder.get(convertView, R.id.chars);
			convertView.setSoundEffectsEnabled(false);
			String str = BaseActivity.CHARS.get(position);
			if (!TextUtils.isEmpty(str)) {
				chars.setText(str);
			} else {
			}
			if (position < 9) {
				tv.setText((position + 1) + "");
			} else {
				switch (position) {
				case 9:
					tv.setText("*");
					break;
				case 10:
					tv.setText("0");
					break;
				case 11:
					tv.setText("#");
					break;
				}
			}

			return convertView;
		}
	}

	/** 显示最近通话和搜索结果的adapter */
	private ContactsDialPadAdapter mAdapter;
	/** 用于实现T9搜索 */
	ContactsHelper mContactsHelper;
	private Map<Integer, Integer> map = new HashMap<Integer, Integer>();
	AudioManager mAudioManager;
	int mFriendsCount = 0;
	/** 拨号键盘 */
	GridView mGridView;
	/** 最近通话 */
	private List<RecentCallsBean> mListRecentCalls;
	/** 显示连接中的头部view */
	private View mHeaderView;
	Activity mContext;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mListRecentCalls = new ArrayList<RecentCallsBean>();
		mContactsHelper = ContactsHelper.getInstance(getActivity()
				.getApplicationContext());
		mContext = getActivity();
	}

	private void loadHistoryCalls() {
		JSONObject json = BaseActivity.getBaseParams(mContext);
		try {
			json.put(KEY_PAGE_NUM, 0);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mHttpClient.post(FUNCTION_GET_CALL_HISTORY, json, new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {

			}

			@Override
			public void onReceiveData(String data, String msg) {
				mListRecentCalls.clear();
				mListRecentCalls.addAll(JsonUtils
						.parseList(data, RecentCallsBean.class));
				mAdapter.notifyDataSetChanged();
			}
		});
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 300:
				mGridView.post(new Runnable() {

					@Override
					public void run() {
						// mAdapter = new ContactsDialPadAdapter(getActivity(),
						// mList);
						// mAdapter.setReplaceText(getTextViewText(R.id.dial));
						// mListView.setAdapter(mAdapter);
						queryFriends(mPhoneContacts);
					}
				});

				break;
			}
		};
	};

	List<SuperFriendsBean> mListSuperFriendsBean;

	private ListView mListView;

	private List<PhoneContactsBean> mPhoneContacts;

	/**
	 * 真实的好友
	 */
	List<SuperFriendsBean> mRealFriends;

	/** 标题栏的搜索栏 */
	private View mSearchView;
	private SuperFriendsBean mSuperFriends;

	List<SuperFriendsBean> mTemp;

	private TextView mTextViewDial;

	SoundPool spool;

	@Override
	public int getLayoutId() {
		return R.layout.fragment_dial_pad;
	}

	private ArrayList<PhoneContactsBean> getPeopleInPhone2() {
		ArrayList<PhoneContactsBean> list = new ArrayList<PhoneContactsBean>();

		Cursor cursor = mContext.getContentResolver().query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
				null, null); // 获取手机联系人
		while (cursor.moveToNext()) {

			int indexPeopleName = cursor.getColumnIndex(Phone.DISPLAY_NAME); // people
																				// name
			int indexPhoneNum = cursor.getColumnIndex(Phone.NUMBER); // phone
																		// number

			String strPeopleName = cursor.getString(indexPeopleName);
			String strPhoneNum = cursor.getString(indexPhoneNum);
			PhoneContactsBean map = new PhoneContactsBean();

			map.setNick_name(strPeopleName);
			PinyinUtil.chineseStringToPinyinUnit(map.getNick_name(),
					map.getNamePinyinUnits());
			map.setPhone(strPhoneNum);
			map.setContactsFromPhone(true);
			list.add(map);
		}
		if (!cursor.isClosed()) {
			cursor.close();
			cursor = null;
		}
		Collections.sort(list);
		mPhoneContacts = list;
		return list;
	}

	private void checkConnection() {
		if (!UCSService.isConnected()) {
			mContext.startService(
					new Intent(mContext, CallConnectionService.class));
			mHeaderView.setVisibility(View.VISIBLE);
		} else {
			mHeaderView.setVisibility(View.GONE);
		}
	}

	private void onConnectSuccess() {
		mHeaderView.setVisibility(View.GONE);
	}

	/**
	 * 加载拨号音
	 */
	private void loadSound() {
		if (spool != null) {
			return;
		}
		spool = new SoundPool(11, AudioManager.STREAM_SYSTEM, 5);
		map.put(10, spool.load(mContext, R.raw.dtmf0, 0));
		map.put(0, spool.load(mContext, R.raw.dtmf1, 0));
		map.put(1, spool.load(mContext, R.raw.dtmf2, 0));
		map.put(2, spool.load(mContext, R.raw.dtmf3, 0));
		map.put(3, spool.load(mContext, R.raw.dtmf4, 0));
		map.put(4, spool.load(mContext, R.raw.dtmf5, 0));
		map.put(5, spool.load(mContext, R.raw.dtmf6, 0));
		map.put(6, spool.load(mContext, R.raw.dtmf7, 0));
		map.put(7, spool.load(mContext, R.raw.dtmf8, 0));
		map.put(8, spool.load(mContext, R.raw.dtmf9, 0));
		map.put(11, spool.load(mContext, R.raw.dtmf11, 0));
		map.put(9, spool.load(mContext, R.raw.dtmf12, 0));
	}

	/**
	 * 加载所有的好友
	 */
	public void loadSuperFriend() {
		JSONObject json = BaseActivity.getBaseParams(mContext);
		try {
			json.put("i_pagenum", 0);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mHttpClient.post(FUNCTION_GET_FRIEND_LIST, json, new MyAjaxCallBack() {

			@Override
			public void onReceiveData(String data, String msg) {
				mRealFriends = JsonUtils.parseList(data, SuperFriendsBean.class);
				Collections.sort(mRealFriends);
				mFriendsCount = mRealFriends.size();
				// 查找已经是超号用户的联系人
				if (mPhoneContacts != null) {
					List<SuperFriendsBean> friends = new ArrayList<SuperFriendsBean>();
					for (SuperFriendsBean phone : mPhoneContacts) {
						for (SuperFriendsBean f : mRealFriends) {
							if (f.getPhone().equals(phone.getPhone())) {
								((PhoneContactsBean) phone).setSuperNum(true);
								friends.add(phone);
								// continue;
							}
						}
					}
					mListSuperFriendsBean.removeAll(friends);
					// mPhoneContacts.removeAll(friends);
					Collections.sort(mPhoneContacts);
				}
				ManagerFactory.createManager(PhoneContactsBean.class).saveList(
						mPhoneContacts);
				mListSuperFriendsBean.addAll(0, mRealFriends);
				ManagerFactory.createManager(SuperFriendsBean.class).saveList(
						mRealFriends);
				mContactsHelper.setBaseContacts(mListSuperFriendsBean);
				mHandler.sendEmptyMessage(300);
			}

			@Override
			public void onReceiveError(String msg, String errorCode) {
			}
		});
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.btn_dial:
			final View grid = findViewById(R.id.grid_area);
			if (grid.getVisibility() == View.GONE) {
				grid.setVisibility(View.VISIBLE);
				return;
			}
			String phone = mTextViewDial.getText().toString();
			if (TextUtils.isEmpty(phone)) {
				return;
			}
			SuperFriendsManager manager = (SuperFriendsManager) ManagerFactory
					.createManager(SuperFriendsBean.class);
			SuperFriendsBean mFriends = manager.findSuperFriendsByPhone(phone);
			if (mFriends == null) {
				searchFriends(phone);
			} else {
				startActivity(new Intent(mContext, OutCallActivity.class)
						.putExtra(KEY_DATA, mFriends));
			}
			break;
		case R.id.delete:
			String text = mTextViewDial.getText().toString();
			if (!TextUtils.isEmpty(text)) {
				mTextViewDial.setText(text.substring(0, text.length() - 1));
				mTemp = searchList(mTextViewDial.getText().toString(), mListSuperFriendsBean);
			}
			break;
		case R.id.to_chat:
			if (mSuperFriends != null && !mSuperFriends.isContactsFromPhone()) {
				startActivity(new Intent(mContext, ChatActivity.class)
						.putExtra(KEY_DATA, mSuperFriends));
			}
			break;
		case R.id.search_area:
			startActivity(new Intent(mContext, SearchUserActivity.class));
			break;
		case R.id.plus:
			startActivity(new Intent(mContext,
					AddSuperFriendsActivity.class));
			break;
		}
	}

	private ConnectionListener mConnectionListener;

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		mContext.unregisterReceiver(mConnectionListener);
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		if (mListSuperFriendsBean == null) {
			mListSuperFriendsBean = new ArrayList<SuperFriendsBean>();
		}
		mConnectionListener = new ConnectionListener();
		mContext.registerReceiver(mConnectionListener,
				new IntentFilter(ACTION_CONNECTION_SUCCESS));
		loadSound();
		mSearchView = findViewById(R.id.search_area);
		mAudioManager = (AudioManager) mContext.getSystemService(
				Context.AUDIO_SERVICE);
		mTextViewDial = (TextView) findViewById(R.id.dial);
		mGridView = (GridView) findViewById(R.id.gridview);
		mListView = (ListView) findViewById(R.id.list);
		mHeaderView = findViewById(R.id.header);
		// mListView.addHeaderView(mHeaderView, null, false);
		final View grid = findViewById(R.id.grid_area);
		mListView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch (event.getActionMasked()) {
				case MotionEvent.ACTION_MOVE:
					if (grid.getVisibility() == View.VISIBLE) {
						grid.startAnimation(AnimationUtils.loadAnimation(
								mContext, R.anim.push_out__up_to_down));
						grid.setVisibility(View.GONE);
					}
					break;
				}

				return false;
			}
		});
		mGridView.setAdapter(new GridAdapter());
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				final SuperFriendsBean superFriends = (SuperFriendsBean) mListView
						.getAdapter().getItem(position);
				// mTextViewDial.setText(superFriends.getPhone());

				if (superFriends instanceof RecentCallsBean) {
					SuperFriendsManager friendsManager = (SuperFriendsManager) ManagerFactory
							.createManager(SuperFriendsBean.class);
					mSuperFriends = friendsManager
							.findSuperFriendsByPhone(superFriends.getPhone());
					if (mSuperFriends == null) {
						searchFriends(superFriends.getPhone());
					} else {
						startActivity(new Intent(mContext,
								OutCallActivity.class).putExtra(KEY_DATA,
								mSuperFriends));
					}

					return;
				}
				mSuperFriends = superFriends;
				if (superFriends.isContactsFromPhone()) {
					if (TextUtils.isEmpty(superFriends.getPhoto())) {
						// startActivity(new Intent(mContext,
						// NotAFriendsActivity.class).putExtra(KEY_DATA,
						// superFriends));
						searchFriends(superFriends.getPhone(),
								new MyAjaxCallBack() {

									@Override
									public void onReceiveData(String data,
											String msg) {
										try {
											SuperFriendsBean mSuperFriends = JsonUtils
													.parse(data.substring(1,
															data.length() - 1),
															SuperFriendsBean.class);
											if (mSuperFriends != null) {
												startActivity(new Intent(
														mContext,
														FriendsDetailActivity.class)
														.putExtra(KEY_DATA,
																mSuperFriends));
											} else {
												startActivity(new Intent(
														mContext,
														NotAFriendsActivity.class)
														.putExtra(KEY_DATA,
																superFriends));
											}
										} catch (Exception e) {
											startActivity(new Intent(
													mContext,
													NotAFriendsActivity.class)
													.putExtra(KEY_DATA,
															superFriends));
										}
									}

									@Override
									public void onReceiveError(String msg,
											String errorCode) {

									}

								});
					} else {
						startActivity(new Intent(mContext,
								FriendsDetailActivity.class).putExtra(KEY_DATA,
								superFriends));
					}
				} else {
					startActivity(new Intent(mContext,
							OutCallActivity.class).putExtra(KEY_DATA,
							mSuperFriends));
				}
				// if (!TextUtils.isEmpty(superFriends.getVo_id())) {
				// startActivity(new Intent(mContext, ChatActivity.class)
				// .putExtra(KEY_DATA, superFriends));
				// }
			}
		});
		mListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					final int position, long id) {
				SuperFriendsBean mFriends = (SuperFriendsBean) mAdapter
						.getItem(position);
				if (mFriends instanceof RecentCallsBean) {
					Builder mBuilder = new Builder(mContext);
					mBuilder.setItems(R.array.long_press_menus_single,
							new OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// RecentCallsManager.getInstance(
									// mContext).deleteCall(
									// mRecentCalls.get(position));
									// mAdapter.notifyDataSetChanged();
									deleteRecentCall(
											mListRecentCalls.get(position),
											position);
								}
							});
					mBuilder.setTitle(R.string.choose_operation);
					mBuilder.setNegativeButton(android.R.string.cancel, null);
					mBuilder.show();
				}
				return true;
			}
		});
		mAdapter = new ContactsDialPadAdapter<RecentCallsBean>(mContext,
				mListRecentCalls);
		mListView.setAdapter(mAdapter);
		mTextViewDial.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable s) {
				if (s == null || s.length() == 0) {
					mTextViewDial.setVisibility(View.GONE);
					mSearchView.setVisibility(View.VISIBLE);
					mAdapter = new ContactsDialPadAdapter<RecentCallsBean>(
							mContext, mListRecentCalls);
					mListView.setAdapter(mAdapter);
				} else {
					mTextViewDial.setVisibility(View.VISIBLE);
					mSearchView.setVisibility(View.GONE);
					if (s.length() > 1) {
						mTemp = searchList(mTextViewDial.getText().toString(),
								mListSuperFriendsBean);
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}
		});
		mGridView.setSoundEffectsEnabled(false);
		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position < 12 && position != 9) {
					play(position);
				}
				if (position < 9) {
					mTextViewDial.append((position + 1) + "");

				}
				if (position == 10) {
					mTextViewDial.append("0");
				}

			}
		});
		view.findViewById(R.id.btn_dial).setOnClickListener(this);
		view.findViewById(R.id.delete).setOnClickListener(this);
		view.findViewById(R.id.to_chat).setOnClickListener(this);
		// view.findViewById(R.id.search_area).setOnClickListener(this);
		view.findViewById(R.id.plus).setOnClickListener(this);
		view.findViewById(R.id.delete).setOnLongClickListener(
				new OnLongClickListener() {

					@Override
					public boolean onLongClick(View v) {
						mTextViewDial.setText("");
						return true;
					}
				});
		readContacts();
		checkConnection();
	}

	private void deleteRecentCall(RecentCallsBean calls, final int position) {
		JSONObject json = BaseActivity.getBaseParams(mContext);
		try {
			json.put("i_callid", calls.getCallid());
			json.put("i_user1", calls.getUser1());
			json.put("i_user2", calls.getUser2());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		showProgressDialog(R.string.deleting);
		
		
		mHttpClient.post(FUNCTION_DELETE_CALL_HISTORY, json,
				new MyAjaxCallBack() {

					@Override
					public void onReceiveError(String msg, String errorCode) {
						cancelProgressDialog();
					}

					@Override
					public void onReceiveData(String data, String msg) {
						cancelProgressDialog();
						mListRecentCalls.remove(position);
						mAdapter.notifyDataSetChanged();
					}
				});
	}

	@Override
	public void onResume() {
		super.onResume();
		loadHistoryCalls();
		// Collections.sort(mRecentCalls);
		mAdapter.notifyDataSetChanged();
	}

	/**
	 * 播放拨号音
	 * 
	 * @param id
	 */
	private void play(int id) {
		int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		int current = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

		float value = (float) 0.7 / max * current;
		spool.setVolume(spool.play(map.get(id), value, value, 0, 0, 1f), value,
				value);
	}

	/**
	 * 在服务器上对比通讯录和好友
	 */
	private void queryFriends(List<PhoneContactsBean> contacts) {
		IS_SUPER.clear();
		if (contacts == null || contacts.isEmpty()) {
			return;
		}
		String phones = "";
		for (PhoneContactsBean phoneContacts : contacts) {
			phones += phoneContacts.getPhone() + ";";
		}
		if (TextUtils.isEmpty(phones)) {
			return;
		}
		phones = phones.substring(0, phones.length() - 1);
		AjaxParams mAjaxParams = new AjaxParams();
		mAjaxParams.put("i_userid", BaseActivity.getUser(mContext)
				.getUserid() + "");
		mAjaxParams.put("i_phones", phones);
		mHttpClient.post(FUNCTION_CHECK_PHONES, mAjaxParams,
				new MyAjaxCallBack() {
					@Override
					public void onReceiveData(String data, String msg) {
						List<SuperFriendsBean> mFriends = JsonUtils.parseList(data,
								SuperFriendsBean.class);
						if (mFriends != null && !mFriends.isEmpty()) {
							for (SuperFriendsBean s : mFriends) {
								// s.setContactsFromPhone(true);
								IS_SUPER.put(s.getPhone(), true);
							}
							// mFriends.removeAll(mRealFriends);
							// mList.addAll(mFriendsCount, mFriends);
							// mAdapter.notifyDataSetChanged();

						}
					}

					@Override
					public void onReceiveError(String msg, String errorCode) {
					}
				});
	}

	private void readContacts() {
		if (!mListSuperFriendsBean.isEmpty()) {
			mHandler.sendEmptyMessage(300);
			return;
		}
		new Thread() {
			public void run() {
				try {
					mListSuperFriendsBean.addAll(getPeopleInPhone2());
				} catch (Exception e) {
					e.printStackTrace();
				}
				loadSuperFriend();

			};
		}.start();

	}

	private void searchFriends(String phone) {
		searchFriends(phone, new MyAjaxCallBack() {

			@Override
			public void onReceiveData(String data, String msg) {
				try {
					SuperFriendsBean mSuperFriends = JsonUtils.parse(
							data.substring(1, data.length() - 1),
							SuperFriendsBean.class);
					if (mSuperFriends != null
							&& mSuperFriends.getVo_id() != null) {
						startActivity(new Intent(mContext,
								OutCallActivity.class).putExtra(KEY_DATA,
								mSuperFriends));
					} else {
						showToast(R.string.super_number_not_found);
					}
				} catch (Exception e) {
					showToast(R.string.super_number_not_found);
				}
			}

			@Override
			public void onReceiveError(String msg, String errorCode) {
				showToast(R.string.super_number_not_found);
			}
		});
	}

	private void searchFriends(String phone, MyAjaxCallBack callBack) {
		JSONObject json = BaseActivity.getBaseParams(mContext);
		try {
			json.put("i_key", phone);
			json.put("i_type", 0);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mHttpClient.post(FUNCTION_SEARCH_USER, json, callBack);
	}

	/**
	 * 搜索联系人
	 * 
	 * @param str
	 * @param data
	 * @return
	 */
	private List<SuperFriendsBean> searchList(String str, List<SuperFriendsBean> data) {
		if (str.isEmpty()) {
			// mContactsHelper.setBaseContacts(mList);
			return mListSuperFriendsBean;
			// mAdapter = new ContactsDialPadAdapter(mContext, mList);
			// mAdapter.setReplaceText(getTextViewText(R.id.dial));
			// mListView.setAdapter(mAdapter);
			// return mList;
		}

		final List<SuperFriendsBean> SuperFriends = new ArrayList<SuperFriendsBean>();
		mContactsHelper.parseT9InputSearchContacts(str);
		SuperFriends.addAll(mContactsHelper.getSearchContacts());
		// mContactsHelper.setBaseContacts(SuperFriends);
		// for (SuperFriends c : data) {
		// if (c.isContactsFromPhone()) {
		// if (c.getPhone().contains(str)) {
		// SuperFriends.add(c);
		// }
		// } else {
		// if (c.getSuid().contains(str)) {
		// SuperFriends.add(c);
		// }
		// }
		// }
		mAdapter = new ContactsDialPadAdapter(mContext, SuperFriends);
		mAdapter.setReplaceText(getTextViewText(R.id.dial));
		mListView.setAdapter(mAdapter);
		return data;
	}

	@Override
	public void toggle() {
		View v = findViewById(R.id.grid_area);
		if (v == null) {
			return;
		}
		if (v.getVisibility() == View.VISIBLE) {
			v.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_out__up_to_down));
			v.setVisibility(View.GONE);
		} else {
			v.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_in_down_to_up));
			v.setVisibility(View.VISIBLE);
		}
	}

	class ConnectionListener extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (ACTION_CONNECTION_SUCCESS.equals(action)) {
				onConnectSuccess();
			}
			if (ACTION_CONNECTION_FAILED.equals(action)) {
				mHeaderView.setVisibility(View.VISIBLE);
			}
		}

	}

	@Override
	public void toggleUp() {
		// TODO Auto-generated method stub
		
	}
}
